var express = require('express');
var router = express.Router();
var connection = require('../db/sql.js')
var user = require('../db/userSql.js')
let jwt = require('jsonwebtoken')

//添加购物车数据
router.post('/api/addCart', function(req, res, next) {
	//后端接收前端的参数
	let goodsId = req.body.goodsId;
	//token
	let token = req.headers.token;
	let tokenObj = jwt.decode(token);
	console.log(tokenObj)
	//查询用户
	connection.query(`select * from user where tel = ${tokenObj.tel}`,function(error,results){
		//用户id
		let uId = results[0].id;
		//查询商品
		connection.query(`select * from goods_list where id=${goodsId}`,function(err,result){
			let goodsName = result[0].name;
			let goodsPrice = result[0].price;
			let goodsImgUrl = result[0].imgUrl;
			connection.query(`insert into goods_cart (uId,goods_id,goods_name,goods_price,goods_num,goods_imgUrl) values ("${uId}","${goodsId}","${goodsName}","${goodsPrice}","1","${goodsImgUrl}")`,function(e,r){
			   res.send({
				   data:{
					   code:200,
					   success:true,
					   msg:'添加成功'
				   }
			   }) 
			})
		})
	})
})

//注册
router.post('/api/register',function(req,res,next){
	let params = {
		userTel : req.body.phone,
		userPwd : req.body.pwd
	}
	connection.query( user.queryUserTel( params ) ,function(error,results){
		if(error) throw error;
		if( results.length > 0 ){
			res.send({
				code:200,
				data:{
					success:true,
					msg:'用户已存在，请登录！',
					data:results[0]
				}
			})
		}else{

			connection.query( user.inserData ( params ),function(err,result){
				connection.query( user.queryUserTel( params ) , function(e,r){
					res.send({
						code:200,
						data:{
							success:true,
							msg:'注册成功！登录成功',
							data:r[0]
						}
					})
				})
			})
		}
	})
	
})


//手机号密码登录
router.post('/api/login',function(req,res,next){
	let params = {
		userTel : req.body.userTel,
		userPwd : req.body.userPwd
	}
	
	connection.query( user.queryUserTel(params),function(error,results){
		if( results.length > 0 ){
			connection.query(user.queryUserPwd(params),function(err,result){
				if(result.length > 0){
					res.send({
						code:200,
						data:{
							msg:'登录成功',
							success:true,
							data:result[0]
						}
					})
				}else{
					//密码不对
					res.send({
						code:302,
						data:{
							msg:'密码不对',
							success:false
						}
					})
				}
			})
		}else{
			//手机号不存在
			res.send({
				code:301,
				data:{
					msg:'手机号不存在',
					success:false
				}
			})
		}
	} )
})



